using MediatR;
using Microsoft.EntityFrameworkCore;
using WMS.Api.Application.Commands.Records;
using WMS.Common;
using WMS.Domain;
using WMS.Infrastructure;

namespace WMS.Api.Application.CommandHandlers.Records
{
    /// <summary>
    /// 记录表分页查询命令处理器
    /// </summary>
    public class GetRecordsPagedQueryHandler : IRequestHandler<GetRecordsPagedQuery, ApiResult<PagedList<Record>>>
    {
        private readonly IBaseRepository<Record> _recordRepo;

        public GetRecordsPagedQueryHandler(IBaseRepository<Record> recordRepo)
        {
            _recordRepo = recordRepo;
        }

        public async Task<ApiResult<PagedList<Record>>> Handle(GetRecordsPagedQuery request, CancellationToken cancellationToken)
        {
            ApiResult<PagedList<Record>> result = new ApiResult<PagedList<Record>>("分页查询记录");

            try
            {
                // 获取基础查询
                var query = _recordRepo.GetNewAllList();

                // 应用筛选条件

                if (request.PayType.HasValue)
                {
                    query = query.Where(r => r.PayType == request.PayType.Value);
                }

                if (request.StartDate.HasValue)
                {
                    query = query.Where(r => r.PayDate >= request.StartDate.Value);
                }

                if (request.EndDate.HasValue)
                {
                    // 设置为当天的23:59:59，确保包含整天
                    var endDate = request.EndDate.Value.Date.AddDays(1).AddSeconds(-1);
                    query = query.Where(r => r.PayDate <= endDate);
                }

                // 按支付日期降序排序
                query = query.OrderByDescending(r => r.PayDate);

                // 获取总记录数
                var totalCount = await query.CountAsync();

                // 获取分页数据
                var items = await query
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync();

                // 创建分页结果
                var pagedList = new PagedList<Record>
                {
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize,
                    TotalCount = totalCount,
                    TotalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize),
                    Items = items
                };

                result.data = pagedList;
                result.isSuc = true;
                result.msg = "查询成功";
                result.code = StatusCodeEnum.Ok;
            }
            catch (Exception ex)
            {
                result.isSuc = false;
                result.msg = $"查询失败：{ex.Message}";
                result.code = StatusCodeEnum.Fail;
            }

            return result;
        }
    }
} 